<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="会员姓名" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        新增
      </el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="加载中" border fit highlight-current-row>
      <!-- <el-table-column label="头像" width="80" align="center">
        <template slot-scope="scope">
          <el-avatar v-if="scope.row.avatar" :src="scope.row.avatar" :size="40" />
          <el-avatar v-else :size="40">{{ scope.row.name ? scope.row.name.charAt(0) : 'U' }}</el-avatar>
        </template>
      </el-table-column> -->
      <el-table-column label="姓名">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.userName }}
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center">
        <template slot-scope="scope">
          {{ scope.row.email }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template slot-scope="scope">
          {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <!-- 移除状态列 -->
      <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="warning" size="mini" @click="handlePassword(row)">
            修改密码
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <!-- 用户表单弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form ref="userForm" :model="userForm" :rules="rules" label-width="80px">
        <!-- <el-form-item label="头像" prop="avatar">
          <el-input v-model="userForm.avatar" placeholder="请输入头像URL" />
        </el-form-item> -->
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 移除状态开关表单项 -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码弹框 -->
    <el-dialog title="修改密码" :visible.sync="passwordDialogVisible" width="500px">
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getUserList, register, updateUser, deleteUser } from '@/api/user'

export default {
  name: 'UserList',
  components: { Pagination },
  data() {
    // 密码确认校验
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {

      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        name: undefined
      },
      dialogVisible: false,
      dialogTitle: '',
      userForm: {
        id: undefined,
        name: '',
        userName: '',
        email: '',
        phone: '',
        gender: 1,
        avatar: ''
      },
      passwordDialogVisible: false,
      passwordForm: {
        id: undefined,
        password: '',
        confirmPassword: ''
      },
      passwordRules: {
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        if (response.code === 200) {
          this.list = response.data.rows
          this.total = response.data.total
        } else {
          this.$message.error(response.message || '获取用户列表失败')
        }
        this.listLoading = false
      }).catch(error => {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleCreate() {
      this.dialogTitle = '新增用户'
      this.userForm = {
        id: undefined,
        name: '',
        userName: '',
        email: '',
        phone: '',
        gender: 1,
        avatar: ''
      }
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.dialogTitle = '编辑用户'
      this.userForm = Object.assign({}, row)
      this.dialogVisible = true
    },
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        deleteUser(row.id).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        }).catch(error => {
          console.error('删除用户失败:', error)
          this.$message.error('删除用户失败')
        })
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
        }
      }
    },
    submitForm() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.userForm.id) {
            // 模拟更新
            updateUser(this.userForm).then(response => {
              if (response.code === 200) {
                this.$message.success('更新成功')
                this.dialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.message || '更新失败')
              }
            }).catch(error => {
              console.error('更新用户失败:', error)
              this.$message.error('更新用户失败')
            })
          } else {
            register(this.userForm).then(response => {
              if (response.code === 200) {
                this.$message.success('新增成功')
                this.dialogVisible = false
                this.getList()
              } else {
                this.$message.error(response.message || '新增失败')
              }
            }).catch(error => {
              console.error('新增用户失败:', error)
              this.$message.error('新增用户失败')
            })
          }
          this.dialogVisible = false
          this.getList()
        }
      })
    },
    handlePassword(row) {
      this.passwordForm.id = row.id
      this.passwordForm.password = ''
      this.passwordForm.confirmPassword = ''
      this.passwordDialogVisible = true
    },
    submitPassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          updateUser(this.passwordForm).then(response => {
            if (response.code === 200) {
              this.$message.success('修改成功')
              this.passwordDialogVisible = false
            } else {
              this.$message.error(response.message || '修改失败')
            }
          }).catch(error => {
            console.error('修改密码失败:', error)
            this.$message.error('修改密码失败')
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
  margin-right: 10px;
}
</style>
